import { Graph, Minimap ,Util ,Tooltip } from '@antv/g6'
import './shape'
var fontSize  = 12
var minWidth = 160
var maxWidth = 300
var textWidth = 0
var nodes = []   //画布上所有的节点
  // 文本超出隐藏 (字段, 最大长度, 字体大小)
  const fittingString = (str) => {
      const ellipsis = '...';
      const ellipsisLength = Util.getTextSize(ellipsis, fontSize)[0];
      let currentWidth = 0
      let res = str;
      const pattern = new RegExp('[\u4E00-\u9FA5]+'); // distinguish the Chinese charactors and letters
      str.split('').forEach((letter,i) => {
          if (currentWidth > maxWidth - ellipsisLength) return;
          if (pattern.test(letter)) {
              // Chinese charactors
              currentWidth += fontSize;
          } else {
              // get the width of single letter according to the fontSize
              currentWidth += Util.getLetterWidth(letter, fontSize);
          }
          if (currentWidth > maxWidth - ellipsisLength) {
              res = `${str.substr(0,i)}${ellipsis}`;
          }
      });
      return res;
  };
  // 获取文本的长度
  const getTextSize = (str) => {
      let width = Util.getTextSize(str, fontSize)[0];
      textWidth = width
      return width > maxWidth ? maxWidth : (width < minWidth ? minWidth : width);

  }

export default class FlowGraph {
  initGraph (container) {
    this.minimap = new Minimap({
      className: 'minimap',
      viewportClassName: 'minimapViewport',
      type: 'delegate',
      size: [110, 110],
      delegateStyle: {
        stroke: '#000', // 描边颜色
        fill: '#eea', // 填充颜色
        lineWidth: 1, // 描边宽度
        opacity: 1, // 透明度
        fillOpacity: 1 // 填充透明度
      }
    })
    this.tooltip = new Tooltip({
      className:'toolTip',
      offsetX: 10,
      offsetY: 20,
      shouldBegin(e){
        // console.log(e.target.get('name'))
        // e.item.getContainer().findAll(item=>{
        //   if(item.get('type') == 'rect'&&item.attr('name')==undefined&&fittingString(e.item.getModel().label).indexOf('...')!==-1){
        //     console.log(item)
        //     return true
        //   }else{
        //     return false
        //   }
        // })
        if(fittingString(e.item.getModel().label).indexOf('...')!==-1&&e.target.get('name') == 'tooltip-response'){
          return true
        }else{
          return false
        }
      },
      getContent(e) {
        const outDiv = document.createElement('div');
        outDiv.style.width = Util.getTextSize(e.item.getModel().label, fontSize)[0] + 10 + 'px';
        outDiv.innerHTML = `
          <ul>
            <li>${e.item.getModel().label}</li>
          </ul>`
          return outDiv
      },
      itemTypes: ['node']
    })
    this.graph = new Graph({
      container: container,
      width: container.clientWidth,
      height: container.clientHeight,
      fitCenter:true,
      // fitView:true,
      // fitViewPadding:20,
      modes: {
        default: ['drag-canvas', 'zoom-canvas', 'drag-node']
      },
      plugins: [this.minimap,this.tooltip],
      defaultEdge: {
        // ... 其他配置
        type:'loop',
        loopCfg: {
          position: 'bottom',
          // dist: 100,
          clockwise: false,
        },
      },
      layout: {
        type: 'dagre',
        rankdir: 'LR', // layout 的方向。T：top；B：bottom；L：left；R：right
        // align: 'DR', // 节点对齐方式。默认值是 undefined，代表对齐到中心。U：upper；D：down；L：left；R：right
        nodesepFunc: (e) => {   //竖直间距
            return e.field.length*16
            // return 50
        },
        ranksepFunc: (e) => {
          const textWidth1 = getTextSize(fittingString(e.label))
          if(textWidth1 <= minWidth){
            return 70
          }else if(textWidth1 >minWidth && textWidth1 <= maxWidth){
            return 200
          }
        }   //水平间距
      }
    })
  }
  renderData (nodes, edges) {
    this.graph.data({ nodes, edges })
  }

  render () {
    this.graph.render()
  }
  downloadFullImage(name){
    this.graph.downloadFullImage(name,'image/png', {
      // backgroundColor: '#ddd',
      padding: [30, 15, 15, 15],
    });
  }
  destroy () {
    this.graph.destroy()
  }

  clear () {
    this.graph.clear()
  }
}
